<template>
    <div class="card-content">
      <div class="content-wrapper">
        <div class="left-content">

          <div class="top-section">
            <h2 class="spot-name">
              {{ spot.spotName }}
              <span class="spot-english-name">{{spot.englishName}}</span>
              <div class="favorite-container">
                <i 
                  :class="{'fas fa-heart': isFavorite, 'far fa-heart': !isFavorite}" 
                  class="favorite-icon" 
                  @click="toggleFavorite" 
                  @mouseover="showTooltip = true" 
                  @mouseleave="showTooltip = false"
                ></i>
                <span v-if="showTooltip" class="tooltip">{{ isFavorite ? '取消收藏' : '收藏该景点' }}</span>
              </div>
            </h2>
            <div class="spot-info">
              <div class="rating-box">
                <el-rate
                    v-model="value"
                    disabled
                    show-score
                    text-color="#F5F5F5"
                    :colors="['#FF0000', '#FFCC00', '#00CC00']"
                    score-template="{value} / 5"
                />
              </div>
              <a href="#comments" class="spot-reviews">13.5万条评价></a>
            </div>
            <div class="spot-badge">
              <template v-if="spot.spotRankTags && spot.spotRankTags.length">
                <a
                  v-for="(tag, index) in spot.spotRankTags"
                  :key="'rank-' + index"
                  href="#rankList"
                :class="['rank-tag', rankTagClass(tag.dimension)]"
                >
                  {{ tag.tagName }} &gt;
                </a>
              </template>
            
              <!-- 特点标签 -->
              <template v-if="spot.tags && spot.tags.length">
                <span
                  v-for="(tag, index) in spot.tags"
                  :key="'tag-' + index"
                  class="badge"
                >
                  {{ tag.tagName }}
                </span>
              </template>
            </div>
          </div>
       
          <div class="middle-section">
            <div class="spot-time">
                <i class="fas fa-clock"></i>
                <span>开放时间：</span>
                <span>{{spot.openTime}}</span>
                <i class="fas fa-chevron-right"></i>
                <el-tag :type="isOpen ? 'success' : 'danger'">{{ isOpen ? '开放中' : '关闭中' }}</el-tag>
            </div>

            <i class="fas fa-map-marker-alt"></i>
            <span>地址：</span>
            <span>{{spot.address}}</span>
            <el-button type="text" :icon="MapIcon" size="large">地图</el-button>
          </div>

          <div class="bottom-section">
            <div class="comment">
              <div class="comment-title">
                <h3>游客评论：</h3>
                <a href="#comments" class="more-comments">更多评论</a>
              </div>
              <div class="comment-header">
                <img :src="showComment[0]?.user?.avatar || 'default-avatar.png'" alt="User Avatar" class="avatar">
                <div class="user-info">
                  <span class="username">{{ showComment[0]?.user?.userName || '暂时没有人' }}</span>
                
                </div>
              </div>
              <div class="comment-text">{{ showComment[0]?.remark || '快来抢沙发'}}</div>
            </div>
            <!-- 可以添加更多评论 -->
          </div>
            
        </div>
        
        <div class="right-content">
          <div class="description">
            <SpotsDesc />
          </div>
        </div>
      </div>
    </div>
    <!-- <div v-if="showModal" class="modal-overlay">
      <div class="modal">
        <h3>选择收藏夹</h3>
        <ul>
          <li v-for="folder in folders" :key="folder.folderId"
              @click="selectedFolderId = folder.folderId"
              :class="{ active: selectedFolderId === folder.folderId }">
            {{ folder.name }}
          </li>
        </ul>
        <div class="modal-actions">
          <button @click="showModal = false">取消</button>
          <button @click="confirmFavorite" :disabled="!selectedFolderId">确认</button>
        </div>
      </div>
    </div> -->
     <!-- 用 el-dialog 替换你的 modal -->
     <el-dialog v-model="showModal" title="选择收藏夹" width="400px" :close-on-click-modal="false">
      <ul class="folder-list">
        <li v-for="folder in folders" :key="folder.folderId"
            @click="selectedFolderId = folder.folderId"
            :class="{ active: selectedFolderId === folder.folderId }">
          {{ folder.name }}
        </li>
      </ul>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showModal = false">取消</el-button>
          <el-button type="primary" @click="confirmFavorite" :disabled="!selectedFolderId">确认</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref,defineProps,computed, defineEmits,onMounted,watch} from 'vue';
import SpotsDesc from './SpotsDesc.vue';
import MapIcon from '../icons/MapIcon.vue';  
import {favouriteAdd,removeFavorite ,userAllFavourite} from "@/api/bookmark.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import {readComment} from "@/api/comment.js";
import {getSpotClass, getTopSpot,getSpotShow ,checkFavoriteStatus} from "@/api/destinations.js";
import dayjs from 'dayjs';
import { useStore } from 'vuex' //
const props = defineProps({
  spot: {
    type: Object,
    required: true
  }
});
const value = ref(4.4);
const store = useStore();
const emit = defineEmits(['doSomething'])
const showModal = ref(false); // 控制弹窗显示
const isFavorite = ref(0);
const showTooltip = ref(false);
const selectedFolderId = ref(null); // 选中的收藏夹 ID
const isOpen = computed(() => {
  const openTime = props.spot.openTime; // e.g., "07:30-18:00"
  if (!openTime || !openTime.includes('-')) return true; // 默认开放

  const [startStr, endStr] = openTime.split('-');
  const now = dayjs(); // 当前时间对象
  const start = dayjs(now.format('YYYY-MM-DD') + ' ' + startStr);
  const end = dayjs(now.format('YYYY-MM-DD') + ' ' + endStr);

  return now.isAfter(start) && now.isBefore(end);
});
const spotId= computed(() => {
  return  props.spot.spotId; // e.g., "07:30-18:00"
});
const rankTagClass = (dimension) => {
  switch (dimension) {
    case '评分':
      return 'rank-score'
    case '热度':
      return 'rank-hotness'
    case '点赞':
      return 'rank-likes'
    default:
      return ''
  }
}

const folders = ref([
    ]);
    const userId = store.state.userInfo.userId; // 获取用户 ID

    // 构造所有收藏状态的请求

  
  const data1 = ref({
    userId: userId,
    bindId: null,
    type: 4
  });

  watch(() => props.spot, (newSpot) => {
  if (newSpot && newSpot.spotId) {
    data1.value.bindId = newSpot.spotId;
    value.value=newSpot.score;
    getComment(newSpot.spotId);
      getfavorite(); // 确保传值后就能触发收藏状态判断
  }
}, { immediate: true });
    // 并行发送请求，等待所有请求完成

const toggleFavorite = () => {

  data1.value.bindId=props.spot.spotId;
  if (isFavorite.value) {
removeFavorite(data1.value)
  .then((res) => {
   isFavorite.value = 0; // 更新 UI
    ElMessage.success(res.data || '您已经取消收藏！');
  })
  .catch((error) => {
    console.error("取消收藏失败:", error);
  });
} else {
// 添加收藏
showModal.value = true;

}
}

const triggerParentFn = () => {
  emit('doSomething', '参数可以是任意值')
}

const confirmFavorite=()=>{

data1.value.folderId=selectedFolderId.value;
favouriteAdd(data1.value)
          .then((res) => {

            showModal.value = false;
            triggerParentFn();
            ElMessage.success(res.data || '收藏成功！');
            getfavorite();
          })
          .catch((error) => {
            console.error("添加收藏失败:", error);
          });
   }
  
const getallfavorites = () => {
    userAllFavourite({
      userId: store.state.userInfo.userId,
      name: "",
      folderId: null,
    }).then(res => {
      if (res.state === 0 && res.data) {

        folders.value = res.data;

      }
    }).catch(error => {
      console.error("获取收藏数据失败:", error);
    });
  };
  const getfavorite = () => {
    data1.value.bindId = props.spot.spotId;
 console.log(`output-data1.value`,data1.value)
    checkFavoriteStatus(data1.value).then((res) => {
        
      if(res.data>0)
         {
         isFavorite.value = 1;
         }else{
          isFavorite.value = 0;
         }



      })
  };
  const showComment=ref({})
const getComment=(bindId)=>{
  readComment({status:0,bindId:bindId

  }).then((res)=>{
console.log(`output->res`,res.data)
showComment.value=res.data;
  })
}
onMounted(() => {
  getallfavorites();
 

})
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');
  .content-wrapper {
    display: flex;
    justify-content: space-between;
    
  }
  
  .left-content {
    flex: 1;
    margin-right: 20px;
  }
  
  .right-content {
    display: flex;
    flex: 1;
  }
  
  .top-section {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: #e1e0e0 1px solid;
    text-align: left;
  }

  .spot-name {
    font-size: 1.5rem;
    font-weight: bold;
    margin: 0px;
    display: flex;
    align-items: center;
  }

  .spot-english-name {
    font-size: 0.875rem;
    color: #666;
    margin-left: 5px;
  }

  .favorite-container {
    position: relative;
    display: inline-block;
  }

  .favorite-icon {
    margin-left: 10px;
    cursor: pointer;
    color: black;
    transition: color 0.3s;
    font-size: 1.2rem;
  }

  .favorite-icon:hover {
    color: red;
  }

  .favorite-icon.fas {
    color: deepskyblue; /* 固定填充颜色 */
  }

  .tooltip {
    margin-left: 10px;
    font-size: 0.8rem;
    color: #333;
    background-color: #fff;
    border: 1px solid #ddd;
    padding: 2px 5px;
    border-radius: 3px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 100%; /* 使提示框出现在图标右边 */
    white-space: nowrap;
  }

  .spot-info {
    margin-top: 5px;
    font-size: 0.9rem;
    color: #333;
  }

  .spot-rating {
    color: #f1f6f7;
    background-color: #0e9aa7;
    border-radius: 5px;
    padding: 0px 5px;
    margin-right: 10px;
  }


  .spot-reviews {
    color: #0066cc;
    text-decoration: none;
    margin-left: 5px;
  }

  .spot-badge {
    margin-top: 5px;
  }

  .badge {
    display: inline-block;
    background-color: rgba(69, 88, 115, 0.1);
    color: #333;
    padding: 2px 5px;
    border-radius: 3px;
    margin-left: 5px;
    font-size: 0.8rem;
  }


  .rank-tag {
    display: inline-block;

    color: #333;
    padding: 2px 5px;
    border-radius: 3px;
    margin-right: 5px;
    font-size: 0.8rem;
    text-decoration: none;

}

.rank-score {
  background-color: #ffcc00;
  color: #333;
}

.rank-hotness {
  background-color: #ff6b6b;
}

.rank-likes {
  background-color: #6bc5ff;
}

  .middle-section {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: #e1e0e0 1px solid;
    text-align: left;
  }

  .spot-time {
    margin-bottom: 10px;
  }

  .bottom-section {
    border-radius: 10px, 10px, 0, 0;
    margin-top: 5px;
  }
  
  .middle-section i {
    margin-right: 5px;
  }
  
  .description {
    border: 1px solid #ddd;
    padding: 10px;
    border-radius: 5px;
    flex: 1;
  }

  .comment {
    background-color: rgba(44, 89, 229, 0.05);
    padding: 10px;
    border-radius: 5px;
    margin-bottom: 10px;
  }

  .comment-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .comment-title h3 {
    font-size: 1rem;
    margin: 0;
    text-align: left;
  }

  .more-comments {
    color: #0066cc;
    text-decoration: none;
    font-size: 0.9rem;
  }

  .more-comments:hover {
    text-decoration: underline;
  }

  .comment-header {
    display: flex;
    align-items: center;
    height: 20px; /* 设置高度为20px */
  }

  .avatar {
    width: 20px; /* 调整头像大小 */
    height: 20px; /* 调整头像大小 */
    border-radius: 50%;
    margin-right: 10px; /* 添加外间距 */
  }

  .user-info {
    display: flex;
    align-items: center;
  }

  .username {
    font-weight: bold;
    margin-right: 10px; /* 添加外间距 */
  }

  .rating-box {
    background-color: #333; /* 亚光黑 */
    color: #fff;
    padding: 0 10px;
    border-radius: 20px; /* 两边是半圆的圆角矩形 */
    display: inline-block;
  }

  .comment-text {
    margin-top: 10px;
    margin-bottom: 10px;
    text-align: left;
    color: #999;
    font-size: 0.875rem; /* 调小字号 */
  }
/* 加上 */
.folder-list {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 300px;
  overflow-y: auto;
}

.folder-list li {
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 8px;
  background-color: #f5f5f5;
  transition: 0.3s;
}

.folder-list li:hover {
  background-color: #e0e0e0;
}

.folder-list li.active {
  background-color: #409EFF;
  color: white;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>